import axios from "axios";
import * as lodash from "lodash";
import {BACKEND_PATH, uploadPath} from "@/config/properties";
import {convertRequestDate} from "vijay-util";
import {initHttpInterceptor} from "@/interceptor";

/*** ================初始化====================== ***/
const defaultHeaders = () => {
    const header = {"X-Access-Token": sessionStorage.getItem("X-Access-Token")};
    return header;
};
const httpInstance = axios.create({
    baseURL: BACKEND_PATH,
    // transformRequest: [function (data, {post, put}) {
    //     post['Content-Type'] = "application/json";
    //     put['Content-Type'] = "application/json";
    //     return JSON.stringify(convertRequestDate(data))
    // }],
});
initHttpInterceptor(httpInstance)
/*** ================请求====================== ***/
async function requestByUpload(obj, path = uploadPath) {
    const formData = lodash.reduce(obj, (formData, val, key) => {
        formData.append(key, val);
        return formData;
    }, new FormData());
    const headers = {...defaultHeaders(), 'Content-Type': 'multipart/form-data'};
    const res = await httpInstance.post(path, formData, {headers});
    return res.data.message;
}
async function requestByGet(url, params = {}, config = {}) {
    if (!url) return;
    const res = await httpInstance.get(url, {
        params,
        headers: defaultHeaders(),
        ...config
    });
    return res.data.result || {};
}
async function requestByPost(url, data = {}) {
    if (!url) return;
    const config = {headers: defaultHeaders()};
    const res = await httpInstance.post(url, data, config);
    return res.data.result || {};
}
async function requestByPut(url, data = {}) {
    if (!url) return;
    const config = {headers: defaultHeaders()};
    const res = await httpInstance.put(url, data, config);
    return res.data.result || {};
}
export {
    requestByGet, requestByPost, requestByUpload,requestByPut
}
